import * as Sentry from "@sentry/nextjs";
import { getMessageStream } from "@typebot.io/bot-engine/apiHandlers/getMessageStream";
import { StreamingTextResponse } from "@typebot.io/legacy/ai";
import { NextResponse } from "next/server";

export const dynamic = "force-dynamic";

const responseHeaders = {
  "Access-Control-Allow-Origin": "*",
  "Access-Control-Allow-Methods": "POST, OPTIONS",
  "Access-Control-Expose-Headers": "Content-Length, X-JSON",
  "Access-Control-Allow-Headers": "*",
};

export async function OPTIONS() {
  return new Response("ok", {
    headers: {
      "Access-Control-Allow-Origin": "*",
      "Access-Control-Allow-Methods": "POST",
      "Access-Control-Expose-Headers": "Content-Length, X-JSON",
      "Access-Control-Allow-Headers": "*",
    },
  });
}

export async function POST(
  req: Request,
  { params }: { params: Promise<{ sessionId: string }> },
) {
  const { sessionId } = await params;
  const body = await req.text();
  const messages = body ? JSON.parse(body).messages : undefined;
  const { stream, status, message, typebotId } = await getMessageStream({
    sessionId,
    messages,
  });
  if (!stream)
    return NextResponse.json({ message }, { status, headers: responseHeaders });

  Sentry.setTag("typebotId", typebotId);
  Sentry.captureMessage("Is using /api/v1/sessions/[sessionId]/streamMessage");

  return new StreamingTextResponse(
    stream.pipeThrough(createStreamDataTransformer()),
    {
      headers: responseHeaders,
    },
  );
}

const createStreamDataTransformer = () => {
  const encoder = new TextEncoder();
  const decoder = new TextDecoder();
  return new TransformStream({
    transform: async (chunk, controller) => {
      const decodedChunk = decoder.decode(chunk);
      if (decodedChunk[0] !== "0") return;
      controller.enqueue(encoder.encode(JSON.parse(decodedChunk.slice(2))));
    },
  });
};
